package co.fitstart.weapp.api.web.controller.course;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;

import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.User;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.CourseScheduleService;
import co.fitstart.weapp.api.service.CourseSigninService;
import co.fitstart.weapp.api.service.UserService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/signin")
public class CourseSigninController {

    private static final Logger logger = LoggerFactory.getLogger(CourseSigninController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private CourseScheduleService courseScheduleService;

    @Autowired
    private CourseSigninService courseSigninService;

    /**
     * 
     * @param scheduleId
     * @param unionid
     * @return
     */
    @RequestMapping(value = "/schedules/{scheduleId}/confirm", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult confirm(@PathVariable("scheduleId") Long scheduleId,
                              @RequestParam("unionid") String unionid,
                              @RequestParam("message") String message) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseSchedule courseSchedule = courseScheduleService.load(scheduleId);
            
            courseRoundService.validate(student, courseSchedule);
            
            courseSigninService.sigin(courseSchedule, message);
            
            httpResult.success().message("签到成功");
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("signinConfirm() error", e);
            httpResult.fail("500").message("签到失败");
        }
        
        return httpResult;
    }
    
    /**
     * 
     * @param scheduleId
     * @param unionid
     * @param message
     * @return
     */
    @RequestMapping(value = "/course-schedules/{scheduleId}/validate-signin", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult validateSignin(@PathVariable("scheduleId") Long scheduleId,
                                     @RequestParam("unionid") String unionid,
                                     @RequestParam("message") String message) {
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseSchedule courseSchedule = courseScheduleService.load(scheduleId);
            
            // validate course first
            courseRoundService.validate(student, courseSchedule);
            
            // validate signin message
            courseSigninService.validate(courseSchedule, message);
            httpResult.success().message("验证签到信息成功");
            
        } catch (BusinessException e) {
            logger.error("validateSignin - ", e);
            httpResult.fail("500").message(e.getMessage());
        } catch (Exception e) {
            logger.error("validateSignin - ", e);
            httpResult.fail("500").message("签到信息错误");
        }
        
        return httpResult;
    }
    
    @RequestMapping(value = "/course-schedules/{scheduleId}/signin-success", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult success(@PathVariable("scheduleId") Long scheduleId,
                              @RequestParam("unionid") String unionid) {
        HttpResult httpResult = new HttpResult();
        
        try {
            
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseSchedule courseSchedule = courseScheduleService.load(scheduleId);
            
            // validate course first
            courseRoundService.validate(student, courseSchedule);
            int finishCount = courseSchedule.getScheduleStatus().isFinish() ? courseSchedule.getCourseRound().getFinished() : courseSchedule.getCourseRound().getFinished() < courseSchedule.getCourseRound().getCourseAmount() ? courseSchedule.getCourseRound().getFinished() + 1 : courseSchedule.getCourseRound().getCourseAmount();
            
            httpResult.success().data("courseSchedule", courseSchedule)
                                .data("finishCount", finishCount)
                                .data("currentDate", new Date())
                                .data("courseName", courseSchedule.getCourse().getName())
                                .data("coachAvatar", courseSchedule.getCoach().getProfile() == null ? null : courseSchedule.getCoach().getProfile().getAvatar())
                                .message("加载信息成功");
            
        } catch (BusinessException e) {
            logger.error("success - ", e);
            httpResult.fail("500").message(e.getMessage());
        } catch (Exception e) {
            logger.error("success - ", e);
            httpResult.fail("500").message("加载信息错误");
        }
        
        return httpResult;
    }
}
